package com.shj.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.shj.mapper.SysRoleDao;
import com.shj.model.PageRequest;
import com.shj.model.PageResult;
import com.shj.model.SysRole;
import com.shj.model.SysRoleMenu;
import com.shj.util.PageUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * (SysRole)表服务实现类
 *
 * @author makejava
 * @since 2020-03-12 12:57:32
 */
@Slf4j
@Service("sysRoleService")
public class SysRoleService {

    @Resource
    private SysRoleDao sysRoleDao;
    @Resource
    private SysRolePowerService sysRolePowerService;

    /**
     * @description 根据roleId查找
     * @author songhuajian
     * @date 2020/3/24 13:36
     */
    public SysRole queryByRoleId(String roleId){
        List<SysRoleMenu> list = sysRolePowerService.findByRoleId(roleId);
        SysRole sysRole = sysRoleDao.queryById(roleId);
        sysRole.setMenus(list);
        return sysRole;
    }

    /**
     * @description 分页查询数据
     * @author songhuajian
     * @date 2020/3/24 13:44
     */
    public PageResult findPage(PageRequest pageRequest){
        return PageUtil.getPageResult(pageRequest, getPageInfo(pageRequest));
    }

    /**
     * @description 调用分页插件完成分页
     * @author songhuajian
     * @date 2020/3/24 13:43
     */
    public PageInfo<SysRole> getPageInfo(PageRequest pageRequest){
        int pageNume = pageRequest.getPageNum();
        int pageSize = pageRequest.getPageSize();
        PageHelper.startPage(pageNume, pageSize);

        List<SysRole> list = sysRoleDao.queryAll(pageRequest.getTitle());
        return new PageInfo<SysRole>(list);
    }

    /**
     * @description 添加数据
     * @author songhuajian
     * @date 2020/3/24 13:46
     */
    @Transactional(rollbackFor = Exception.class)
    public void insert(SysRole sysRole){
        // 添加角色
        sysRoleDao.insert(sysRole);
        // 添加角色权限
        List<String> list = sysRole.getCheckList();
        sysRolePowerService.addRolePower(list, sysRole.getRoleId());
    }

    /**
     * @description 更新数据
     * @author songhuajian
     * @date 2020/3/24 13:47
     */
    @Transactional(rollbackFor = Exception.class)
    public void update(SysRole sysRole){
        // 更新角色信息
        sysRoleDao.update(sysRole);
        // 更新角色权限信息
        List<String> list = sysRole.getCheckList();
        sysRolePowerService.updateRolePower(list, sysRole.getRoleId());
    }

    /**
     * @description 删除数据
     * @author songhuajian
     * @date 2020/3/24 13:48
     */
    @Transactional(rollbackFor = Exception.class)
    public void delete(String roleId){
        // 删除角色信息
        sysRoleDao.deleteById(roleId);
        // 删除角色权限信息
        sysRolePowerService.delete(roleId);
    }
}